package com.leo.common.db.exception;

import com.leo.common.core.enums.ExceptionCodeEnum;
import com.leo.common.core.model.Result;
import com.leo.common.core.util.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;

/**
 * <p>
 * 数据库全局异常处理器
 * </p>
 *
 * @author ：Leo
 * @since ：2021-03-01 14:04
 */
@Order(2)
@Slf4j
@RestControllerAdvice
public class GlobalDbExceptionHandler {

	@Resource
	MessageUtils messageUtils;

	/**
	 * validation Exception
	 * @param e 异常类
	 * @return Result
	 */
	@ExceptionHandler({ DuplicateKeyException.class })
	@ResponseStatus(HttpStatus.OK)
	public Result<Void> handleSqlIntegrityConstraintViolationException(DuplicateKeyException e) {
		log.error("主键约束异常 ex={}", e.getMessage(), e);
		String mst = messageUtils.get("duplicate.key.exception");
		Result<Void> result = new Result<>();
		result.setCode(ExceptionCodeEnum.SERVER_ERROR.getCode());
		result.setMsg(mst);
		return result;
	}

}
